package com.maven.booksystem.interceptor;

import com.maven.booksystem.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
// 1. 定义拦截器
public class LoginInterceptor implements HandlerInterceptor {


    // 相应方法 执行 之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("LoginInterceptor ⽬标⽅法执⾏前执⾏..");

        // 我们 校验 是否登录 就是在这里 来进行 操作的
        HttpSession session = request.getSession(false);
        if (session != null &&
                session.getAttribute(Constants.SESSION_USER_KEY) != null) {
            return true;
        }
        response.setStatus(401);
        return false;
    }





    // 相应方法 执行 之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle ⽬标⽅法执⾏后执⾏..");
    }

}
